package models

import (
	"awesomeProject/config"
	"awesomeProject/logger"
	"fmt"

	_ "github.com/denisenkom/go-mssqldb" // SQL Server driver
	"github.com/go-xorm/xorm"
)

var loggerl = logger.InitLog()

// ConnectDB initializes the XORM database connection and returns the Engine instance.
func ConnectDB() (*xorm.Engine, error) {
	d, _ := config.GetConfig()
	user := d.User
	password := d.Password
	host := d.Server
	port := d.Port
	database := d.Database
	loggerl.Debugf("Connecting to database: %s  password %s", user, password)
	var engine *xorm.Engine
	// dsn := fmt.Sprintf("sqlserver://%s:%s@%s?database=%s&encrypt=disable", user, password, host, database)
	dsn := fmt.Sprintf("sqlserver://%s:%s@%s:%d?database=%s&encrypt=disable", user, password, host, port, database)
	// dsn := fmt.Sprintf("server=%s;port=%d;database=%s;integratedSecurity=true;encrypt=disable", host, port, database)

	engine, err := xorm.NewEngine("mssql", dsn)
	if err != nil {
		loggerl.Errorf("Failed to connect database: %v", err)
		return nil, fmt.Errorf("failed to connect database: %v", err)
	}

	engine.ShowSQL(true)
	engine.SetMaxIdleConns(10)
	engine.SetMaxOpenConns(100)
	engine.SetConnMaxLifetime(0)
	// Optional: You can set some global configurations for the engine here.
	// For example, to set the logger:
	// engine.SetLogger(xorm.NewSimpleLogger(os.Stdout))

	loggerl.Debug("Connected to database success")
	return engine, nil
}

// CloseDB closes the XORM database connection.
func CloseDB(engine *xorm.Engine) {
	err := engine.Close()
	if err != nil {
		loggerl.Errorf("Failed to close database: %v", err)
		return
	}
	loggerl.Debug("Closed database connection")
}
